package com.hrt.manage.product.controllor;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.GiftDetail;
import com.hrt.bean.GiftGroup;
import com.hrt.bean.GiftInfor;
import com.hrt.bean.GiftTypeDir;
import com.hrt.manage.product.service.GiftDetailService;
import com.hrt.manage.product.service.GiftGroupService;
import com.hrt.manage.product.service.GiftInforService;
import com.hrt.manage.product.service.GiftTypeDirService;
import com.hrt.util.WebParams;
import com.hrt.util.upload.Plupload;
import com.hrt.util.upload.UploadUtil;

@Controller
@RequestMapping("manage/giftInfo")
public class GiftInforControllor extends BaseController<GiftInfor> {
	
	//礼品基本信息
	@Autowired
	private GiftInforService giftInforService;
	
	//礼品规格
	@Autowired
	private GiftDetailService giftDetailService;

	//礼品组合
	@Autowired
	private GiftGroupService giftGroupService;
	
	//礼品分类目录明细
	@Autowired
	private GiftTypeDirService giftTypeDirService;
	
	
	/************---------多图片上传-----------*********/
	private List<File> files;
	@Autowired
	private UploadUtil uploadUtil;
	
	public static final String FileDir = "uploadfile/"; 

	public List<File> getFiles() {
		return files;
	}
	public void setFiles(List<File> files) {
		this.files = files;
	}
	/**********---------多图片上传结束---------********/
	
	
	private GiftDetail iterGD;

	public GiftDetail getIterGD() {
		return iterGD;
	}

	public void setIterGD(GiftDetail iterGD) {
		this.iterGD = iterGD;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) {
		Map resultMap = new HashMap();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);

		setTotalCount(giftInforService.totalCount());

		List<GiftInfor> resultList = giftInforService.queryByPage(
				getPageIndex(), getPageSize());
		setList(resultList);
		/** demo */
		/*
		 * int i = 0; for (Iterator<GiftInfor> iters = resultList.iterator();
		 * iters.hasNext();) { GiftInfor iterGI = iters.next(); List<GiftDetail>
		 * listGD = giftDetailService.searchIspush(iterGI); for
		 * (Iterator<GiftDetail> iterGDs = listGD.iterator();
		 * iterGDs.hasNext();) { iterGD = iterGDs.next();
		 * if(iterGD.getIspush()==1){ i++; } } if(i!=0){
		 * iterGD.getGiftInfor().setIspush(1);
		 * this.giftInforService.updateGiftInfor(iterGD.getGiftInfor());
		 * System.out.println(iterGD.getGiftInfor().getId()+"====="); }else{
		 * iterGD.getGiftInfor().setIspush(0);
		 * this.giftInforService.updateGiftInfor(iterGD.getGiftInfor()); } }
		 */
		/** ============================== */
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	/**
	 * 查看
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();

		list = giftInforService.queryByPage(getPageIndex(), getPageSize());
		setTotalCount(giftInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		view.addObject("pageResult", page);
		return view;

	}
	/**
	 * 根据giftId查找礼品规格
	 * @param giftId
	 * @param request
	 * @param response
	 * @return 礼品规格集合
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/queryGiftDetails")
	@ResponseBody
	public Map queryGiftDetails(
			@RequestParam(value = "giftId", required = true) Long giftId,
			HttpServletRequest request, HttpServletResponse response) {
		Map resultMap = new HashMap();

		List<GiftDetail> resultList = giftInforService.getGiftDetailByGiftId(giftId);
		resultMap.put("resultList", resultList);
		return resultMap;

	}

	/**
	 * 删除
	 * */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
					
					/**删除礼品分类明细*/
					List<GiftTypeDir> listGiftTypeDir= this.giftTypeDirService.getGiftTypeDirByGIId(idArr[idx]);
					if(listGiftTypeDir!=null && listGiftTypeDir.size()>0){
						for (Iterator<GiftTypeDir> iterDir = listGiftTypeDir.iterator(); iterDir.hasNext();) {
							GiftTypeDir gtd = (GiftTypeDir) iterDir.next();
							try {
								//删除礼品分类明细
								this.giftTypeDirService.deleteByOneId(gtd.getId());
							} catch (Exception e) {
								e.printStackTrace();
							}
				        }
					}
					
					/**删除礼品规格*/
					List<GiftDetail> listDateil= this.giftDetailService.getDetailIdforId(idArr[idx]);
					if(listDateil!=null && listDateil.size()>0){
						for (Iterator<GiftDetail> iter = listDateil.iterator(); iter.hasNext();) {
							GiftDetail gd = (GiftDetail) iter.next();
							
							if(gd!=null){
								//删除礼品组合
								List<GiftGroup> listgiftGroup= this.giftGroupService.getGroupIdforId(gd.getId());
								if(listgiftGroup!=null && listgiftGroup.size()>0){
									for (Iterator<GiftGroup> iterGroup = listgiftGroup.iterator(); iterGroup.hasNext();) {
										GiftGroup gigr = (GiftGroup) iterGroup.next();
										try {
											//删除礼品组合
											this.giftGroupService.deleteByOneId(gigr.getId());
										} catch (Exception e) {
											e.printStackTrace();
										}
							        }
								}
							}

							try {
								//删除礼品规格
								this.giftDetailService.deleteByOneId(gd.getId());
							} catch (Exception e) {
								e.printStackTrace();
							}
				        }
					}
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
				
				/**删除礼品分类明细*/
				List<GiftTypeDir> listGiftTypeDir= this.giftTypeDirService.getGiftTypeDirByGIId(Long.parseLong(ids));
				if(listGiftTypeDir!=null && listGiftTypeDir.size()>0){
					for (Iterator<GiftTypeDir> iterDir = listGiftTypeDir.iterator(); iterDir.hasNext();) {
						GiftTypeDir gtd = (GiftTypeDir) iterDir.next();
						System.out.println("GiftTypeDir==>"+gtd.getGiftName());
						try {
							//删除礼品分类明细
							this.giftTypeDirService.deleteByOneId(gtd.getId());
						} catch (Exception e) {
							e.printStackTrace();
						}
			        }
				}
				
				/**删除礼品规格*/
				List<GiftDetail> listDateil= this.giftDetailService.getDetailIdforId(Long.parseLong(ids));
				if(listDateil!=null && listDateil.size()>0){
					for (Iterator<GiftDetail> iter = listDateil.iterator(); iter.hasNext();) {
						GiftDetail gd = (GiftDetail) iter.next();
						
						if(gd!=null){
							/**删除礼品组合*/
							List<GiftGroup> listgiftGroup= this.giftGroupService.getGroupIdforId(gd.getId());
							if(listgiftGroup!=null && listgiftGroup.size()>0){
								for (Iterator<GiftGroup> iterGroup = listgiftGroup.iterator(); iterGroup.hasNext();) {
									GiftGroup gigr = (GiftGroup) iterGroup.next();
									try {
										//删除礼品组合
										this.giftGroupService.deleteByOneId(gigr.getId());
									} catch (Exception e) {
										e.printStackTrace();
									}
						        }
							}
						}
						
						try {
							//删除礼品规格
							this.giftDetailService.deleteByOneId(gd.getId());
						} catch (Exception e) {
							e.printStackTrace();
						}
			        }
				}
			}
		}
		
		//删除礼品基本信息
		try {
			giftInforService.deleteById(idArr);
			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 上架
	 * */
	@RequestMapping(value = "/shelve", method = RequestMethod.POST)
	public @ResponseBody Long[] shelve(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			giftInforService.shelveById(idArr);

			/** demo上架 */
			List<GiftInfor> listGiftInfor = this.giftInforService
					.getByIds(idArr);
			for (Iterator<GiftInfor> iters = listGiftInfor.iterator(); iters
					.hasNext();) {
				GiftInfor iterGI = iters.next();
				List<GiftDetail> listGD = this.giftDetailService
						.searchIspush(iterGI);
				for (Iterator<GiftDetail> iterGDs = listGD.iterator(); iterGDs
						.hasNext();) {
					iterGD = iterGDs.next();
					iterGD.setIspush(1);
					this.giftDetailService.updateGiftDetail(iterGD);
				}
			}
			/** ========================== */

			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 下架
	 * */
	@RequestMapping(value = "/unShelve", method = RequestMethod.POST)
	public @ResponseBody Long[] unShelve(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			giftInforService.unShelveById(idArr);

			/** demo下架 */
			List<GiftInfor> listGiftInfor = this.giftInforService
					.getByIds(idArr);
			for (Iterator<GiftInfor> iters = listGiftInfor.iterator(); iters
					.hasNext();) {
				GiftInfor iterGI = iters.next();
				List<GiftDetail> listGD = this.giftDetailService
						.searchIspush(iterGI);
				for (Iterator<GiftDetail> iterGDs = listGD.iterator(); iterGDs
						.hasNext();) {
					iterGD = iterGDs.next();
					iterGD.setIspush(0);
					this.giftDetailService.updateGiftDetail(iterGD);
				}
			}
			/** ========================== */

			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 添加
	 * */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("giftInfo") GiftInfor gi,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Timestamp createTime = this.giftInforService.getDate();
			gi.setCreateTime(createTime);
			System.out.println("__***----->"+gi.getDetail());
			giftInforService.addGiftInfor(gi);
			response.sendRedirect("list.do");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 跳转到修改页面
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String giId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		List<String> picGiftImg = new ArrayList<String>();
		if (giId != null && !"".equals(giId)) {
			GiftInfor gi = this.giftInforService.getById(new Long(giId));
			if(gi != null){
				//多图片上传
				String picStr = gi.getDetail();
				if(picStr!=null && picStr!="" ){
					String[] picStrArr = picStr.split(",");
//					List<String> picList = new ArrayList<String>();
					for(int f = 0 ;f <picStrArr.length ; f++){
						picGiftImg.add(picStrArr[f]);
					}
					gi.setPicStrs(picGiftImg);
				}
				
				//商品详情
				byte[] buf = gi.getUeditorDetails();
				String strBuf = new String();
				try {
					if(buf!=null && !"".equals(buf)){
						strBuf = new String(buf, "UTF-8");
						gi.setDetails_Str(strBuf);
					}
					if (gi != null) {
						map = transBean2Map(gi);
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

		}
		map.put("picGiftImg", picGiftImg);
		return map;
	}

	/**
	 * 修改
	 * */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("giftInfo") GiftInfor gi,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Timestamp editTime = this.giftInforService.getDate();
			gi.setEditTime(editTime);

			giftInforService.updateGiftInfor(gi);
			response.sendRedirect("list.do");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//图片上传
		@RequestMapping(value = "/upload", method = RequestMethod.POST)
		public void upload(Plupload plupload,HttpServletRequest request, HttpServletResponse response) {
			plupload.setRequest(request);  
	        //文件存储路径  
	        File dir = new File(plupload.getRequest().getSession().getServletContext().getRealPath("/") + FileDir);  
	        try {  
	            //上传文件  
	        	File file = uploadUtil.upload(plupload, dir);  
	            //判断文件是否上传成功（被分成块的文件是否全部上传完成）  
	        	if (file != null) {
	        		//获取上传的图片名称
	        		//全路径
	        		 String UPLOAD_SUCCESS = WebParams.DO_MAIN + request.getContextPath() + "/" + FileDir + file.getName();
	        		System.out.println("sdjshd===>"+UPLOAD_SUCCESS);
	        		byte[] responseBytes = UPLOAD_SUCCESS.getBytes();
	 				response.setContentLength(responseBytes.length);
	 				ServletOutputStream pw = response.getOutputStream();
	 				pw.write(responseBytes);
	 				pw.flush();
	 				pw.close();
	            }else{
	            	String UPLOAD_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";
	            	response.setContentType("application/json");
					final byte[] responseBytes = UPLOAD_ERROR.getBytes();
					response.setContentLength(responseBytes.length);
					ServletOutputStream pw = response.getOutputStream();
					pw.write(responseBytes);
					pw.flush();
					pw.close();
	            }
	        } catch (IllegalStateException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } 
	    } 
	
}
